package com.wenhai.leetcode.tree;

/**
 *https://leetcode-cn.com/problems/maximum-binary-tree/
 *
 * @author wenhai
 * @date   2021/4/8
 */
public class _654最大二叉树 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return findRoot(nums, 0, nums.length );
    }

    private TreeNode findRoot(int[] nums, int l, int r) {
        if (l >= r) {
            return null;
        }
        int maxIndex = l;
        for (int i = l + 1; i < r; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }
        TreeNode treeNode = new TreeNode(nums[maxIndex]);
        treeNode.left = findRoot(nums, l, maxIndex);
        treeNode.right = findRoot(nums, maxIndex + 1, r);
        return treeNode;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
